import { reportForms } from "@/api/index";
import { table } from "@/api";
import { mapState, mapActions } from "vuex";
import { columnsScreen, derives } from "./columns";
import RmsDetail from "@components/table/dialog/RmsDetail"
export default {
  name: "rmsDetails",
  data () {
    return {
      total: 0,
      pageSizeOptions: [10, 20, 50, 100, 500],
      pageNo: 1,
      pageSize: 10,
      combineTr: 7,
      dialogVisible: false,
      loading: false,
      particularYear: '',
      time: '',
      pickDate: '',
      total: '',
      currentYear: '',
      currentMonth: '',
      currentTime: '',
      consigner: '',
      consignerShow: '',
      params: {
        customerName: "",
        carrierName: "",
        page: 1,
        size: 10,
      },
      pickerOptions: {
        onPick: this.getPickDate,
        disabledDate: this.disabledDate
      },
      derive: {},
      consignerObj: {},
      shipData: {},
      shipTime: {},
      allTotal: {},
      tableData: [],
      yearList: [
        { id:0, name: "" },
        { id:1, name: "" }
      ],
      columns: [],
      restaurants: []
    };
  },
  computed: {
    ...mapState({
      tenantId: (state) => state.login.tenantId,
      menuId: (state) => state.menu.menu.menuId
    })
  },
  mounted () {
    this.derive = derives(this.menuId);
    this.loadAll();
    setTimeout(() => {
      this.columns = columnsScreen(this.menuId);
      this.locationInHone();
    },1500);
  },
  methods: {
    // 是否带参
    locationInHone () {
      let now = new Date();
      this.currentYear = now.getFullYear()
      this.currentMonth = now.getMonth() + 1;
      this.currentTime = String(now.getFullYear()) + (this.currentMonth<10?'0' + String(this.currentMonth):String(this.currentMonth));
      this.yearList[0].name = this.currentYear;
      this.yearList[1].name = this.currentYear - 1;
      if (this.menuId == 316) {
        delete this.params.carrierName
      } else if (this.menuId == 330) {
        delete this.params.customerName
      } else {
        delete this.params.carrierName
        delete this.params.customerName
      }
      this.search(2);
    },
    querySearch(queryString, cb) {
      let restaurants = this.restaurants;
      let results
      if (queryString == this.consignerObj.value) {
        results = restaurants;
      } else {
        results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      }
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    async loadAll() {
      let { data } = await reportForms.consignerSearchs({ tenantId: this.tenantId })
      let datas = data.data
      this.restaurants = []
      datas.forEach(item=>{
        this.restaurants.push(
          {
            value: item.customerName,
            ccId: item.ccId,
            relationId: item.relationId,
            type: item.type
          }
        )
      })
    },
    handleSelect(item) {
      console.log(item);
      this.consignerObj = item
    },
    // 切换页数大小
    handleSizeChange () {
      this.search(2);
    },
    // 分页
    handleCurrentChange () {
      this.search(2);
    },
    // 查询
    async search (type) {
      this.params.page = type == 1?1:this.pageNo,
      this.params.size = this.pageSize
      if (this.consignerObj.value) {
        if (this.consigner) {
          this.params.ccId = this.consignerObj.ccId
          this.params.relationId = this.consignerObj.relationId
          this.params.type = this.consignerObj.type
          this.consigner = this.consignerObj.value
          this.consignerShow = this.consignerObj.value
        } else {
          this.consignerObj = {}
          this.deleteConsigner()
          this.consignerShow = '所有发货方'
        }
      } else {
        this.deleteConsigner()
        this.consignerShow = '所有发货方'
      }
      this.tableData = []
      this.loading = true
      let { data } = await reportForms.rmsList(this.params,this.menuId)
      let datas = data.data
      let code = data.code
      if (code === 0) {
          if (this.menuId == 325) {
            this.tableData = datas.records.fee != undefined?[datas.records.fee]:[]
          } else {
            this.tableData = datas.records
          }
          this.loading = false
          this.allTotal = datas.allTotal?datas.allTotal:{}
          this.total = datas.total?datas.total:0
      }
      this.loading = false
    },
    selectMonth (e) {
      console.log(e)
      if (e) {
        this.params.queryStartTime = this.$moment(this.time[0]).format("YYYYMM");
        this.params.queryEndTime = this.$moment(this.time[1]).format("YYYYMM");
      } else {
        this.params.queryStartTime = this.currentTime;
        this.params.queryEndTime = this.currentTime;
      }
    },
    clearYear (e) {
      this.params.year = e;
    },
    // 导出
    async handleExport () {
      if (!this.tableData.length) {
        this.$message.warning("没有可要导出的数据！");
        return false;
      }
      let args = JSON.parse(JSON.stringify(this.params))
      args.page = 1
      let params = {
        args: { ...args },
        name: this.derive.name,
        type: this.derive.type
      };
      await table.submitFormContainer(`/export/task`, params);
      this.searchCount();
      this.$nextTick(() => {
        this.$message.success("导出功能正在后台执行中，请稍后去“导出文件”下载中查看！");
      });
    },
    // 查询导出未读数
    ...mapActions({
      searchCount: "login/exportCount"
    }),
    // 清除发货方条件
    deleteConsigner () {
      delete this.params.ccId;
      delete this.params.relationId;
      delete this.params.type;
      this.consignerObj = {}
      this.consigner = ''
    },
    // 清除
    resetForm () {
      this.time = []
      delete this.params.queryStartTime;
      delete this.params.queryEndTime;
      delete this.params.year;
      delete this.params.ccId;
      delete this.params.relationId;
      delete this.params.type;
      this.consigner = '';
      this.consignerObj = {}
      this.consignerShow = '';
      this.particularYear = '';
      this.consignerShow = '';
      this.locationInHone();
    },
    dialog (data) {
      this.dialogVisible = true;
      this.shipTime = {
        queryStartTime:this.params.queryStartTime,
        queryEndTime:this.params.queryEndTime
      }
      this.shipData = data;
    },
    handleClose () {
      this.dialogVisible = false;
     },
    //限制筛选时效一年
    getPickDate(pick) {
      this.pickDate = pick;
    },
    disabledDate(date) {
      const { minDate, maxDate } = this.pickDate;
      if (minDate && !maxDate) {
        const diff = Math.abs(minDate.valueOf() - date.valueOf());
        if (diff > 1000 * 3600 * 24 * 365) {
          return true;
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并表格
      let num = 3;
      if (columnIndex === 0) {
        if (rowIndex % num === 0) {
          return {
            rowspan: num,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    toFixeTwoPercent  (num) {
      // 小数转百分比，保留两位小数
      num = typeof num === 'undefined' ? 0 : num
      num = num * 100 + ''
      if (num.indexOf('.') === -1) {
        num = num + '.00%'
      } else if (num.split('.')[1].length === 1) {
        num = num + '0%'
      } else {
        num = (num * 1).toFixed(2) + '%'
      }
      return num
    },
    totalType (menuId) {
      let text
      if (menuId == 325 || menuId == 326) {
        text = '总成本：'
      } else if (menuId == 336) {
        text = '总利润：'
      } else {
        text = '总收入：'
      }
      return text
    },
    conversion (val) {
      return JSON.stringify(val?val:0).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      if (this.menuId != 325 && this.menuId != 326 && this.menuId != 312) {
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          let el
          if (index === 0) {
            if (this.menuId == 323 || this.menuId == 324 || this.menuId == 336) {
              el = '总合计：' // 主要代码
            } else {
              el = <p>本页合计：<br/><br/>总合计：</p> // 主要代码
            }
            sums[index] = el
            return;
          }
          if (column.label == '收入（元）') {
            el = this.conversion(this.allTotal.totalAmountIncome)
          } else if (column.label == '运单数（单）' || column.label == '发货方运单（单数）') {
            el = this.conversion(this.allTotal.totalWaybill)
          } else if (column.label == '成本（元）') {
            el = this.conversion(this.allTotal.totalAmountCost)
          } else if (column.label == '利润（元）' || column.label == '实际利润（元）') {
            el = this.conversion(this.allTotal.profits)
          } else if (column.label == '总重量（公斤）' || column.label == '重量（公斤）') {
            el = this.conversion(this.allTotal.totalWeight)
          } else if (column.label == '总体积（方）' || column.label == '体积（方）') {
            el = this.conversion(this.allTotal.totalVolume)
          } else if (column.label == '实际成本率（%）') {
            el = this.conversion(this.allTotal.amountCostRate)
          } else if (column.label == '实际利润率（%）') {
            el = this.conversion(this.allTotal.profitsRate)
          }
          sums[index] = el
          return;
        });
      }
      return sums;
    }
  },
  components: {
    RmsDetail
  }
};